import { reactive } from "vue";
import type { App } from "vue";
import type { piniaInter } from "./index";

export const piniaSymbol = Symbol("pinia");
export let activePinia: piniaInter | undefined;
export const setActivePinia = (pinia: piniaInter) => activePinia = pinia;

export const createPinia = () => {
    const state = reactive<Record<string, any>>({}); // 保存每个store的state

    const pluginList: Function[] = [];
    const pinia: piniaInter = {
        _store: new Map(), // 存放所有的store    { store1 => store, store2 => store }
        _plugin: pluginList,
        state,
        use: (plugin: Function) => {
            pluginList.push(plugin);
            return pinia;
        },
        install: (app: App) => {
            // console.log(app)
            setActivePinia(pinia);

            // 让所有的store都可以获取到这个pinia对象
            // 所有组件都可以通过 app.inject(piniaSymbol)得到pinia对象
            app.provide(piniaSymbol, pinia);
            // 可以通过this.$pinia得到pinia对象
            app.config.globalProperties.$pinia = pinia;
        }
    }

    return pinia;
}